# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community
Edition) available.
Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://opensource.org/licenses/MIT
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
"""

import logging
import traceback

from blueapps.account.components.sops_session.models import UserProxy
from blueapps.core.exceptions.base import MethodError
from django.conf import settings
from django.contrib.auth.backends import ModelBackend
from django.db import IntegrityError

from blueapps import metrics
from blueapps.account import get_user_model
from blueapps.account.conf import ConfFixture
from blueapps.account.utils.http import send
from blueapps.utils import client
from blueapps.utils.tools import resolve_login_url

logger = logging.getLogger("component")

ROLE_TYPE_ADMIN = "1"

# TOKEN_TYPE = "bk_token"


class SopsSessionBackend(ModelBackend):
    def authenticate(self, request=None,username=None,password=None):

        logger.debug(" Enter in SopsSessionBackend")



        # 判断是否传入没传入则返回None
        if username is None or password is None:
            return None

        user_model = get_user_model()

        # debug 模式
        # if username == "admin":
        #     return user_model.objects.get(username=username)


        try:
            user = user_model.objects.get(username=username)
        except user_model.DoesNotExist:
            logger.exception(traceback.format_exc())
            logger.exception("username DoesNotExist")
            return None
        if user.check_password(password):
            return user
        else:
            # password error
            # 判断否验证通过,不通过则返回None
            logger.debug("使用check_password验证用户密码用户不存在、认证失败")
            return None
